﻿using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows.Data;
using ttg_internal.Utilities.UsageVisualizer.Other;

namespace ttg_internal.Utilities.UsageVisualizer.Converter
{
    internal class SubsystemIconConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string subsystemName = value.ToString().ToLower();
            string[] bestMatch = null;
            int bestMatchRate = 0;

            foreach (string[] map in IconMap.Instance.SubsystemMap)
            {
                Debug.Assert(map.Length == 2);
                int match = Math.Min(subsystemName.Length, map[0].Length);
                
                for (int i = 0; i < match; ++i)
                {
                    if (subsystemName[i] != map[0][i])
                    {
                        match = i;
                        break;
                    }
                }

                if (match > bestMatchRate)
                {
                    bestMatchRate = match;
                    bestMatch = map;
                }
            }

            string fileName;
            
            if (bestMatch == null)
            {
                fileName = IconMap.Instance.SubsystemMap.First(str => str[0] == string.Empty)[1];
            }
            else
            {
                fileName = bestMatch[1];
            }

            return Path.Combine(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Devices"), fileName);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
